/*
 * @Author: LF
 * @Description: 登录页
 * @Date: 2020-10-21 08:38:38
 * @LastEditTime: 2020-10-24 09:52:04
 */
import React, { Component } from 'react'
// 引入消息提示框
import { message, Form, Input, Button } from 'antd'
import jwt from 'jsonwebtoken'
import moment from 'moment'
import { userLogin, recordIp } from '@/services/user'

class login extends Component {
  // 登录
  login = (e) => {
    e.preventDefault()
    this.props.form.validateFields(async (err, values) => {
      if (!err) {
        // 发送登录请求
        let { data: res } = await userLogin(values)
        console.log(res);
        // 如果登录失败，则提示错误信息
        if (res && res.ok !== 1) {
          return message.error(res.msg || '发生了一些错误')
        }
        // 如果发现有新消息
        else if (res && res.ok === 1 && res.msgNum !== 0) {
          message.info(`您有${res.msgNum}条新消息，请到我的消息页查看！`)
        }
        // 提示用户登录成功
        message.success(res.msg)
        // 将令牌存到浏览器
        sessionStorage.setItem('token', res.token)
        // 获取用户ip
        let ip = window.returnCitySN.cip
        // 发送用户ip到服务器（记录用户登录信息）
        await recordIp({
          ip,
          username: jwt.decode(res.token).username,
          login_time: moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
        })
        // 一秒后跳转到首页
        setTimeout(() => {
          window.location.href = '/'
        }, 1000)
      }
    })
  }

  render() {
    const { getFieldDecorator } = this.props.form
    return (
      <div className="center-nav">
        <div className="center-nav-left">
          <div className="user-handle-box">
            <h1>登录</h1>
            <hr />
            <Form onSubmit={this.login}>
              <Form.Item>
                {getFieldDecorator('username', {
                  rules: [{ required: true, message: '账号不能为空!' }]
                })(<Input placeholder="请输入账号" />)}
              </Form.Item>
              <Form.Item>
                {getFieldDecorator('password', {
                  rules: [{ required: true, message: '密码不能为空!' }]
                })(<Input.Password placeholder="请输入密码" />)}
              </Form.Item>
              <Form.Item>
                <Button htmlType="submit">登录</Button>
              </Form.Item>
            </Form>
          </div>
        </div>
        <div className="center-nav-right"></div>
      </div>
    )
  }
}

const loginForm = Form.create()(login)
export default loginForm
